﻿//-----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web{    using System;
    using System.Threading;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using AbstractSaaSTemplate.Application.Configuration;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Helpers;
    using OOHM.Framework.Configuration;

    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    /// <summary>
    /// Defines the methods, properties, and events that are common to all application
    /// objects in an ASP.NET application. This class is the base class for applications
    /// that are defined by the user in the Global.asax file.
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// Initializes a new instance of the MvcApplication class.
        /// </summary>
        /// <param name="repositoryForTenancy">The repository to operate 'Tenancy'.</param>
        public MvcApplication(ITenancyRepository repositoryForTenancy) : this(false)
        {            
            // load the repositories
            this.RepositoryForTenancy = repositoryForTenancy;
        }
        
        /// <summary>
        /// Initializes a new instance of the MvcApplication class.
        /// </summary>
        public MvcApplication() : this(true)
        {
        }

        /// <summary>
        /// Initializes a new instance of the MvcApplication class.
        /// </summary>
        /// <param name="instanceDefaultRepositories">A value indicating wether the ctor should or not create instances for the repositories.</param>
        private MvcApplication(bool instanceDefaultRepositories)
            : base()
        {
            // so we can start doing Dependency Injection and working
            // with IoC (Inversion of Control). For that, we create our
            // factories which will be used by the application to figure
            // out the dependencies injected by the modules into the
            // kernel of the application.
            this.ApplicationFactory = new ApplicationFactory();

            // load the repositories
            if (instanceDefaultRepositories)
            {
                this.RepositoryForTenancy = this.ApplicationFactory.CreateRepositoryFor<ITenancyRepository>();
            }
        }
        
        #region Properties

        /// <summary>
        /// Gets a value indicating whether we are unit testing.
        /// </summary>
        public static bool LaunchedFromUnitTest
        {
            get
            {
                return HttpContext.Current.Session["launcher"] as string == "unit-test";
            }
        }

        /// <summary>
        /// Gets the factory of controllers, services and tasks for the application.
        /// </summary>
        public ApplicationFactory ApplicationFactory { get; private set; }

        /// <summary>
        /// Gets the repository to operate 'Tenancy'.
        /// </summary>
        public ITenancyRepository RepositoryForTenancy { get; private set; }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Event Handler for the Start event of the Application.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This is an event handler invoked by the framework and it is not possibly convertable to static.")]
        protected void Application_Start()
        {
            // here we fire all settings registration
            this.RegisterGlobalFilters(GlobalFilters.Filters);
            this.RegisterAreasAndRoutes(RouteTable.Routes);
            this.RegisterViewEngines(ViewEngines.Engines);
            this.RegisterGlobalSettings();

            // and finally, we change the controller factory
            ControllerBuilder.Current.SetControllerFactory(this.ApplicationFactory);
        }

        /// <summary>
        /// Event Handler for the AcquireRequestState event of the Application.
        /// </summary>
        /// <param name="sender">The object which has invoked this event.</param>
        /// <param name="e">The event data.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This is an event handler invoked by the framework and it is not possibly convertable to static.")]
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            var repositoryForSessions = this.ApplicationFactory.CreateRepositoryFor<ISessionRepository>();
            var session = repositoryForSessions.ActiveSession;

            Thread.CurrentThread.CurrentUICulture = session.Culture;
            Thread.CurrentThread.CurrentCulture = session.Culture;
        }

        /// <summary>
        /// Event Handler for the BeginRequest event of the Application.
        /// </summary>
        /// <param name="sender">The object which has invoked this event.</param>
        /// <param name="e">The event data.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This is an event handler invoked by the framework and it is not possibly convertable to static.")]
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (!Configurator.Initialized)
            {
                return;
            }

            if (!Configurator.GetConfigurationByKey<bool>(ConfigurationKeys.Installed))
            {
                return;
            }

            // this will add data tokens setting up the tenant.
            // this can be used by the application to load the tenant information
            this.ProcessRouteDataForTenancy();
        }

        #endregion
    }
}


